import Setting from "@/config/setting";
import Request from "@/utils/request";
import ESQiNiu from "@/utils/ES6qiniu";

const $qiniu = new ESQiNiu();
/**
 * 上传静态文件到CDN
 * @param {string} tempFilePath 临时文件地址
 * @param {string} fileName 文件名
 * @return {string} 上传成功后，静态资源的cdn链接
 */
export default async function uploadFileToCDN(tempFilePath) {
  // 获取文件名称，用于上传自定义key
  // 生成时间戳
  const timestamp = new Date().getTime();
  // 后续修改为正则匹配
  const fileName = tempFilePath
    .split("/")
    [tempFilePath.split("/").length - 1].split(".")[0];
  // 获取七牛的token和key
  //
  const {
    data: {
      data: { fileKey, uploadToken },
    },
  } = await Request.request(
    "GET",
    `${Setting.cdn.getTokenURL}/alipay/media/uploadToken?fileName=${fileName +
      timestamp}`,
    null,
    false
  );
  // 自定义上传key时不用用init的方法
  const options = {
    region: "SCN",
    uptoken: uploadToken,
    key: fileKey,
    domain: Setting.cdn.accessURL,
    shouldUseQiniuFileName: false,
  };

  const res = await new Promise((resolve, reject) => {
    $qiniu.upload(
      tempFilePath,
      (res) => {
        resolve(res);
      },
      (err) => {
        reject(err);
      },
      options
    );
  })
  return (res || {}).fileURL;
}
